(function () {
    'use strict';
    angular.module('vehicleCheckApp').controller('ChecklistPreviewCtrl', ChecklistPreviewCtrl);
    function ChecklistPreviewCtrl($scope, $state, $stateParams,_$toast,$timeout,_DBSerive,_vehicleData) {
		var resultText = {
			pass:{resultText:"放行",resultTextCss:"pass-text"},
			refuse:{resultText:"拒绝",resultTextCss:"refuse-text"},
			change:{resultText:"要求整改",resultTextCss:"change-text"}
		}
        console.log("========$stateParams=========");
		console.log($stateParams);
		var index = parseInt($stateParams.index);
        if($stateParams.revise == "true"){
			$scope.revise = true;
			handleChangeItem(index);
			$scope.result = resultText.change;
		}else if($stateParams.revise == "false"){
			$scope.revise = false;
            _DBSerive.queryNotSubmitList(localStorage.actno).then(function(result){
                console.log("result");
                console.log(result);
                if(result.rows.length > 0 && result.rows.item(0).notSubmitLists){
                       var notSubmitLists = JSON.parse(result.rows.item(0).notSubmitLists);
                        $scope.dataItem = notSubmitLists[index];
                        $scope.notSubmitIndex = index;
                        console.log("==========dataItem===========");
                        console.log($scope.dataItem);
                        var score = 0;
                        var totalPoints = 0;
                        var noNum = 0;
                        angular.forEach($scope.dataItem.checkItems,function(item){
                            totalPoints += item.score;
                            if(item.questionno == 1){
                                if(item.answer == 1){
                                    score += item.score
                                }else{
                                    $scope.result = resultText.refuse;
                                    $scope.dataItem.percent = 0;
                                    $scope.dataItem.ispass = 0;
                                    return;
                                }
                            }else if(item.questionno >=2 && item.questionno <=5){
                                if(item.answer == 1){
                                    score += item.score
                                }else{
                                    noNum++;
                                    if(noNum >=2 ){
                                        $scope.result = resultText.refuse;
                                        $scope.dataItem.percent = 0;
                                        $scope.dataItem.ispass = 0;
                                        return;
                                    }
                                }
                            }else{
                                if(item.answer == 1)
                                    score += item.score;
                            }
                        });
                        var percent = Math.round(score/totalPoints * 100);
                        if(percent <= 70){
                            $scope.result = resultText.refuse;
                            $scope.dataItem.percent = percent;
                            $scope.dataItem.ispass = 0;
                        }else if(percent >= 90){
                            $scope.result = resultText.pass;
                            $scope.dataItem.percent = percent;
                            $scope.dataItem.ispass = 1;
                        }else{
                            $scope.result = resultText.change;
                            $scope.revise = true;
                            saveChangeLists(notSubmitLists, index);
                        }
                }
            });


		}
		
		function saveChangeLists(notSubmitLists, index){
			var changeItem = notSubmitLists[index];
			notSubmitLists.splice(index,1);
            var data = {};
            data.actno = localStorage.actno;
            data.notSubmitLists = notSubmitLists;
           _DBSerive.insertNotSubmitList(data);

            //查询要求修改记录
            _DBSerive.queryReviseList(localStorage.actno).then(function(result){
                var data = {};
                data.actno = localStorage.actno;
                var changeLists = result.rows.length > 0 ? JSON.parse(result.rows.item(0).changeLists): [];
                changeLists.unshift(changeItem);
                data.changeLists = changeLists;
                _DBSerive.insertReviseList(data).then(function(){
                    handleChangeItem(0);
                });
            });
		}
		
		function handleChangeItem(num){
			$scope.changeIndex = num;
            _DBSerive.queryReviseList(localStorage.actno).then(function(result){
                if(result.rows.length > 0 && result.rows.item(0).changeLists){
                    var changeLists = JSON.parse(result.rows.item(0).changeLists);
                    $scope.dataItem = changeLists[num];
                    $scope.noOptions = [];
                    angular.forEach($scope.dataItem.checkItems, function(item){
                        console.log(item.answer)
                        if(item.answer == 2)
                            $scope.noOptions.push(item);
                    });
                }
            });
		}

        $scope.submitCheckItem = function(){
            console.log("===dataItem====");
            console.log($scope.dataItem);
            _vehicleData.submitCheckItem($scope.dataItem).then(function(result){
                var itemrecordids = result.itemrecordids;
                angular.forEach($scope.dataItem.checkItems,function(checkItem){
                    if(checkItem.photos.length > 0){
                        var checkItemId = checkItem.checkitemid;
                        var recorditemid = "";
                        for(var i = 0;i < itemrecordids.length;i++){
                            if(checkItemId == itemrecordids[i].checkitemid){
                                recorditemid = itemrecordids[i].recordItemid;
                                break;
                            }
                        }
                        var param = {};
                        param.recorditemid  = recorditemid;
                        for(i=0;i<checkItem.photos.length;i++){
                            var photo = checkItem.photos[i];
                            param.filename = checkItem.photos[i].substring(checkItem.photos[i].lastIndexOf('/')+1);
                            param.photo = photo;
                            _vehicleData.uploadPic(param);
                        }
                    }
                });
                _DBSerive.queryNotSubmitList(localStorage.actno).then(function(result){
                    console.log(result);
                    if(result.rows.length > 0 && result.rows.item(0).notSubmitLists.length > 0){
                        console.log(result.rows.item(0).notSubmitLists);
                        var notSubmitLists = JSON.parse(result.rows.item(0).notSubmitLists);
                        notSubmitLists.splice($scope.notSubmitIndex, 1);
                        var data = {};
                        data.actno = localStorage.actno;
                        data.notSubmitLists = notSubmitLists;
                        _DBSerive.insertNotSubmitList(data);
                    }
                });
                $timeout(function(){
                    $state.go("checklistResult", {resultText:$scope.result.resultText,resultTextCss:$scope.result.resultTextCss});
                },1000);
            });


        }

		$scope.changeFinish = function(){
			var score = 0;
			var totalPoints = 0;
            console.log($scope.noOptions);
            console.log($scope.dataItem.checkItems);
			angular.forEach($scope.noOptions,function(item){
				angular.forEach($scope.dataItem.checkItems, function(checkItem, i){
					if(checkItem.questionno == item.questionno){
						checkItem = item;
					}
					totalPoints += checkItem.score;
					if(checkItem.answer == 1)
						score += checkItem.score;
				});
			});
			$scope.dataItem.percent = Math.round(score/totalPoints * 100);
			console.log($scope.dataItem);
			if($scope.dataItem.percent >= 90){
				$scope.result = resultText.pass;
				$scope.dataItem.ispass = 1;
			}else{
				$scope.result = resultText.refuse;
				$scope.dataItem.ispass = 0;
			}
			$scope.dataItem.submitTime = new Date().getTime();
			$scope.revise = false;


            _DBSerive.queryReviseList(localStorage.actno).then(function(result){
                var data = {};
                data.actno = localStorage.actno;
                if(result.rows.length > 0 && result.rows.item(0).changeLists){
                   var changeLists = JSON.parse(result.rows.item(0).changeLists);
                    console.log("==changeIndex=="+$scope.changeIndex);
                    changeLists.splice($scope.changeIndex, 1);
                    data.changeLists = changeLists;
                    _DBSerive.insertReviseList(data).then(function(){
                       console.log("success");
                    });
                }
            });


            _DBSerive.queryNotSubmitList(localStorage.actno).then(function(result){
                var data = {};
                data.actno = localStorage.actno;
                var notSubmitLists = result.rows.length > 0 ? JSON.parse(result.rows.item(0).notSubmitLists) : [];
                notSubmitLists.unshift($scope.dataItem);
                data.notSubmitLists = notSubmitLists;
                console.log("===not submit list===");
                console.log(data.notSubmitLists);
                _DBSerive.insertNotSubmitList(data);
            });
			$scope.notSubmitIndex = 0;
		}
		
		$scope.backToList = function(){
			$state.go("pendinglist", {revise:$scope.revise});
		}
    };
})();